package cn.edu.ncepu;

import java.math.BigInteger;

public class KaratsubaMultiplicationBigInteger {

    public static BigInteger mul(BigInteger x0, BigInteger x1, BigInteger y0, BigInteger y1, BigInteger base, int m) {
        BigInteger p0 = x0.multiply(y0);
        BigInteger p1 = x1.multiply(y1);
        BigInteger p2 = x1.add(x0).multiply(y1.add(y0)).subtract(p1).subtract(p0);

        BigInteger p = base.pow(m); // BigInteger自带pow方法，无精度问题

        return p1.multiply(p).multiply(p).add(p.multiply(p2)).add(p0);
    }

    public static void main(String[] args) {
        // 测试用例：1234 * 1432（BigInteger版本）
        BigInteger x0 = BigInteger.valueOf(34);
        BigInteger x1 = BigInteger.valueOf(12);
        BigInteger y0 = BigInteger.valueOf(32);
        BigInteger y1 = BigInteger.valueOf(14);
        BigInteger base = BigInteger.TEN; // 10
        int m = 2;

        BigInteger result = mul(x0, x1, y0, y1, base, m);
        BigInteger expected = BigInteger.valueOf(1234).multiply(BigInteger.valueOf(1432));

        System.out.println("分治法计算结果（BigInteger）：" + result);
        System.out.println("直接乘法结果（BigInteger）：" + expected);
        System.out.println("结果是否一致：" + result.equals(expected));
    }
}